<?php
class PriceInstockPublicBehavior extends Behavior {
	public function run(&$params){  
		$last_price	= $this->getLastPrice();
		$avg_price	= $this->getAvgPrice();
		foreach ((array)$params['detail'] as $k=>$v){
			if($k>0 && $v['product_id']){
				$info['last_price_'.$v['currency_id']]	= floatval($last_price[$v['product_id'].'_'.$v['currency_id']]);
				$info['avg_price_'.$v['currency_id']]	= floatval($avg_price[$v['product_id'].'_'.$v['currency_id']]);
				M('ProductPrice')->where('product_id='.intval($v['product_id']))->save($info);
			}
		}
	}
	
	
	/**
	 * 计算产品的最后一次入库价格
	 *
	 */
	protected  function getLastPrice() {
		$model	= M('Instock');
		$sql	= '
			SELECT instock_detail.price, product_id,instock_id,currency_id
			FROM instock_detail
			WHERE 1 
			GROUP BY product_id, currency_id
			order by instock_id
		';
		$list	= $model->query($sql);
		foreach ((array)$list as $k=>$v){
			$info[$v['product_id'].'_'.$v['currency_id']]	= $v['price']; 
		}
		return $info;
	}
	/**
	 * 计算产品的平均入库价格
	 *
	 */
	protected  function getAvgPrice() {
		$model	= M('Instock');
		$sql	= '
			select sum(quantity*capability*dozen*price)/sum(quantity*capability*dozen)  as price,product_id,currency_id
			from instock_detail where 1 group by product_id,currency_id
		';
		$list	= $model->query($sql);
		foreach ((array)$list as $k=>$v){
			$info[$v['product_id'].'_'.$v['currency_id']]	= $v['price']; 
		}
		return $info;
	}
}


